package com.dts.yjnb.service.controller.admin;

import com.dts.common.annotation.Anonymous;
import com.dts.common.core.controller.BaseController;
import com.dts.common.core.domain.AjaxResult;
import com.dts.common.core.page.TableDataInfo;
import com.dts.yjnb.service.domainDto.AllowancePolicyDTO;
import com.dts.yjnb.service.service.INbAllowancePolicyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 补贴政策Controller
 *
 * @author dts
 */
@Api(tags = "补贴政策管理")
@RestController
@RequestMapping("/yjnb/policy")
@Slf4j
@Anonymous
public class NbAllowancePolicyController extends BaseController
{
    @Autowired
    private INbAllowancePolicyService nbAllowancePolicyService;

    /**
     * 补贴政策分页查询
     */
    @GetMapping("/page")
    @ApiOperation("查看补贴政策列表")
    public TableDataInfo page(AllowancePolicyDTO allowancePolicyDTO)
    {
        log.info("补贴政策分页查询:{}", allowancePolicyDTO);
        TableDataInfo tableDataInfo = nbAllowancePolicyService.pageQuery(allowancePolicyDTO);
        return tableDataInfo;
    }

    /**
     * 删除补贴政策（单个或批量）
     *
     * @param ids 补贴政策ID，单个ID或逗号分隔的多个ID（例如："1" 或 "1,2,3"）
     * @return 结果
     */
    @DeleteMapping("/delete/{ids}")
    @ApiOperation("删除补贴政策（单个或批量）")
    public AjaxResult delete(@ApiParam("补贴政策ID，单个ID或逗号分隔的多个ID") @PathVariable("ids") String ids)
    {
        log.info("删除补贴政策，IDs：{}", ids);
        
        if (ids == null || ids.trim().isEmpty()) {
            return AjaxResult.error("删除失败，ID不能为空");
        }
        
        int result = nbAllowancePolicyService.deleteNbAllowancePolicyByIds(ids);
        
        if (result > 0) {
            log.info("删除补贴政策成功，删除数量：{}", result);
            return AjaxResult.success("删除成功");
        } else {
            log.warn("删除补贴政策失败，未找到对应的记录");
            return AjaxResult.error("删除失败，未找到对应的记录");
        }
    }

    /**
     * 搜索补贴政策信息
     * 支持按标题、作者、来源进行模糊搜索
     */
    @GetMapping("/search")
    @ApiOperation("搜索补贴政策信息。支持通过keyword参数或直接输入搜索词(例如: /search?123)进行搜索")
    public TableDataInfo search(AllowancePolicyDTO searchDTO, HttpServletRequest request)
    {
        // 获取所有查询参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        String defaultKeyword = null;

        for (String paramName : parameterMap.keySet()) {
            if (!"keyword".equals(paramName) && !"title".equals(paramName) &&
                !"authorSource".equals(paramName) && !"page".equals(paramName) &&
                !"pageSize".equals(paramName)) {
                // 直接使用参数名作为搜索词
                defaultKeyword = paramName;
                break;
            }
        }
        if (defaultKeyword != null && !defaultKeyword.isEmpty()) {
            searchDTO.setKeyword(defaultKeyword);
            log.info("使用默认搜索参数: {}", defaultKeyword);
        }

        log.info("搜索补贴政策信息，关键词: {}, 标题: {}, 作者/来源: {}",
                 searchDTO.getKeyword(), searchDTO.getTitle(), searchDTO.getAuthorSource());
        return nbAllowancePolicyService.searchAllowancePolicy(searchDTO);
    }

    /**
     * 新增补贴政策
     */
    @PostMapping("/add")
    @ApiOperation("新增补贴政策")
    public AjaxResult add(@RequestBody AllowancePolicyDTO allowancePolicyDTO)
    {
        log.info("新增补贴政策请求: {}", allowancePolicyDTO);

        try {
            int result = nbAllowancePolicyService.insertAllowancePolicy(allowancePolicyDTO);
            if (result > 0) {
                log.info("新增补贴政策成功");
                return AjaxResult.success("新增成功");
            } else {
                log.error("新增补贴政策失败");
                return AjaxResult.error("新增失败");
            }
        } catch (IllegalArgumentException e) {
            log.warn("有未填写字段: {}", e.getMessage());
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("新增补贴政策异常: {}", e.getMessage(), e);
            return AjaxResult.error("新增过程中发生异常: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询补贴政策详情
     */
    @GetMapping({"/{id}", "/get/{id}"})
    @ApiOperation("查询补贴政策详情")
    public AjaxResult getById(@ApiParam("补贴政策ID") @PathVariable("id") String id)
    {
        log.info("查询补贴政策详情，ID：{}", id);
        AllowancePolicyDTO allowancePolicyDTO = nbAllowancePolicyService.getAllowancePolicyById(id);
        if (allowancePolicyDTO == null) {
            return AjaxResult.error("补贴政策不存在");
        }
        return AjaxResult.success(allowancePolicyDTO);
    }

    /**
     * 修改补贴政策
     */
    @PutMapping("/update")
    @ApiOperation("修改补贴政策")
    public AjaxResult update(@RequestBody AllowancePolicyDTO allowancePolicyDTO)
    {
        log.info("修改补贴政策请求: {}", allowancePolicyDTO);

        try {
            int result = nbAllowancePolicyService.updateAllowancePolicy(allowancePolicyDTO);
            if (result > 0) {
                log.info("修改补贴政策成功");
                return AjaxResult.success("修改成功");
            } else {
                log.warn("修改补贴政策失败，补贴政策不存在或已被删除");
                return AjaxResult.error("修改失败，补贴政策不存在或已被删除");
            }
        } catch (IllegalArgumentException e) {
            log.warn("参数验证失败: {}", e.getMessage());
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("修改补贴政策异常: {}", e.getMessage(), e);
            return AjaxResult.error("修改过程中发生异常: " + e.getMessage());
        }
    }
    
    /**
     * 单个修改发布状态
     */
    @PutMapping("/updateStatus")
    @ApiOperation("单个修改发布状态")
    public AjaxResult updateStatus(@RequestParam String id, @RequestParam Integer status)
    {
        log.info("修改补贴政策发布状态, id:{}, status:{}", id, status);
        try {
            nbAllowancePolicyService.updateStatusById(id, status);
            String message = status == 1 ? "发布成功" : "取消发布成功";
            return AjaxResult.success(message);
        } catch (IllegalArgumentException e) {
            log.warn("参数验证失败: {}", e.getMessage());
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("修改发布状态异常: {}", e.getMessage(), e);
            return AjaxResult.error("修改过程中发生异常: " + e.getMessage());
        }
    }
    
    /**
     * 单个修改推荐状态
     */
    @PutMapping("/updateRecommend")
    @ApiOperation("单个修改推荐状态")
    public AjaxResult updateRecommend(@RequestParam String id, @RequestParam Integer isRecommend)
    {
        log.info("修改补贴政策推荐状态, id:{}, isRecommend:{}", id, isRecommend);
        try {
            nbAllowancePolicyService.updateRecommendById(id, isRecommend);
            String message = isRecommend == 1 ? "推荐成功" : "取消推荐成功";
            return AjaxResult.success(message);
        } catch (IllegalArgumentException e) {
            log.warn("参数验证失败: {}", e.getMessage());
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("修改推荐状态异常: {}", e.getMessage(), e);
            return AjaxResult.error("修改过程中发生异常: " + e.getMessage());
        }
    }

}
